import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Semester } from './entities/semester.entity';
import { CreateSemesterDto } from './dto/create-semester.dto';
import { UpdateSemesterDto } from './dto/update-semester.dto';
import { QuerySemesterDto } from './dto/query-semester.dto';

@Injectable()
export class SemesterService {
  constructor(
    @InjectRepository(Semester)
    private readonly semesterRepo: Repository<Semester>
  ) {}

  async create(createSemesterDto: CreateSemesterDto): Promise<Semester> {
    const semester = this.semesterRepo.create(createSemesterDto);
    return this.semesterRepo.save(semester);
  }

  async findAll(query: QuerySemesterDto): Promise<{
    list: Semester[];
    itemCount: number;
    page: number;
    pageSize: number;
    pageCount: number;
  }> {
    const { page = 1, pageSize = 10, ...filters } = query;
    const skip = (page - 1) * pageSize;
    
    const where: any = {};
    if (filters.name) {
      where.name = Like(`%${filters.name}%`);
    }
    if (filters.status) {
      where.status = filters.status;
    }

    const [data, total] = await this.semesterRepo.findAndCount({
      where,
      skip,
      take: pageSize,
      order: {
        startDate: 'DESC'
      }
    });

    return {
      list: data,
      itemCount: total,
      page,
      pageSize,
      pageCount: Math.ceil(total / pageSize)
    };
  }

  async findOne(id: number): Promise<Semester> {
    const semester = await this.semesterRepo.findOne({
      where: { semester_id: id }
    });
    
    if (!semester) {
      throw new NotFoundException(`学期ID ${id} 不存在`);
    }
    
    return semester;
  }

  async update(id: number, updateSemesterDto: UpdateSemesterDto): Promise<Semester> {
    const semester = await this.findOne(id);
    
    // 合并更新数据
    Object.assign(semester, updateSemesterDto);
    
    return this.semesterRepo.save(semester);
  }

  async remove(id: number): Promise<void> {
    const semester = await this.findOne(id);
    await this.semesterRepo.remove(semester);
  }

  // 获取当前学期
  async getCurrentSemester(): Promise<Semester> {
    const currentSemester = await this.semesterRepo.findOne({
      where: { status: 'current' }
    });

    if (!currentSemester) {
      throw new NotFoundException('当前没有进行中的学期');
    }

    return currentSemester;
  }

  // 获取学期统计信息
  async getSemesterStats(): Promise<any> {
    const stats = await this.semesterRepo
      .createQueryBuilder('semester')
      .select('semester.status', 'status')
      .addSelect('COUNT(*)', 'count')
      .groupBy('semester.status')
      .getRawMany();

    return stats;
  }

  async updateStatus(id: number, newStatus: string): Promise<Semester> {
    const validStatus = ['planned', 'current', 'completed'];
    if (!validStatus.includes(newStatus)) {
      throw new BadRequestException('Invalid semester status');
    }
    
    const semester = await this.findOne(id);
    return this.update(id, { ...semester, status: newStatus });
  }
}
